package com.zzw.springcloud.controller;

import com.zzw.springcloud.bean.Member;
import com.zzw.springcloud.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

//http://localhost:80/member/consumer/selectById?id=2
@Slf4j
@Controller
@RequestMapping("/member/consumer")
public class MemberConsumerController {
    //服务提供方url
    //public static final String MEMBER_SERVICE_PROVIDER_URL = "http://localhost:10000";

    /*
    1.member-service-provider 是服务提供方【集群】 注册到eureka server的名字
    2.也就是服务提供者【集群】对外暴露的名称为member-service-provider
    3.member-service-provider服务目前有两个Availability Zones， 两个实例别名分别是
      member-service-provider:10000, 还有一个是 member-service-provider:10002
    4.还要增加一个注解@LoadBanlanced, 赋予RestTemplate负载均衡的能力, 也就是会根据你的负载均衡来选择某个服务去访问,
      默认是轮询算法, 当然我们也可以自己配置负载均衡算法
     */
    public static final String MEMBER_SERVICE_PROVIDER_URL = "http://member-service-provider";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/selectById/{id}")
    @ResponseBody
    public Result selectById(@PathVariable("id") Integer id) {
        //当你使用带@RibbonClient注解的restTemplate的时候，请求会被ribbon拦截，会将服务名替换成对应的ip端口
        Result result = restTemplate.getForObject(MEMBER_SERVICE_PROVIDER_URL
                + "/member/provider/selectById/" + id, Result.class);
        return result;
    }

    @PostMapping("/insert")
    @ResponseBody
    public Result insert(@RequestBody Member member) {
        Result result = restTemplate.postForObject(MEMBER_SERVICE_PROVIDER_URL
                + "/member/provider/insert", member, Result.class);
        return result;
    }

    @GetMapping("member/consumer/discovery")
    @ResponseBody
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        //遍历所有服务
        for (String service : services) {
            log.info("服务名: {}", service);
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                log.info("ID: {}, host: {}, port: {}, url: {}",
                        instance.getServiceId(), instance.getHost(), instance.getPort(), instance.getUri());
            }
        }
        return discoveryClient;
    }
}
